
from pathlib import Path
from typing import cast
from logging import (
    DEBUG, INFO, WARNING, ERROR, CRITICAL,
    Logger, Formatter, getLogger, StreamHandler, FileHandler, LogRecord
)

from dotfilebackup.settings import (
    APP_NAME, LOG_FORMAT_CONSOLE, LOG_FORMAT_CFGFILE
)


__all__ = ['log', 'add_log_file']


class RedYellowFormatter(Formatter):
    def __init__(self, format:str|tuple[str, str]) -> None:
        super().__init__()

        f2 = ''  # second arg to logging.Formatter
        tf = type(format)
        if (tf == tuple) and (len(format) == 2):
            format, f2 = format[0], format[1]
        elif tf != str:
            raise ValueError('format: expected str or tuple[str, str]')
        format = cast(str, format)

        # grey      = '\x1b[38;21m'
        # blue      = '\x1b[38;5;39m'
        yellow      = '\x1b[38;5;226m'
        red         = '\x1b[38;5;196m'
        # red_bold  = '\x1b[31;1m'
        # purple    = '\x1b[35;1m'
        reset_color = '\x1b[0m'
        self.def_fm        = Formatter(format, f2)
        # self.grey_fm     = Formatter(f'{grey}{format}{reset_color}', f2)
        # self.blue_fm     = Formatter(f'{blue}{format}{reset_color}', f2)
        self.yellow_fm     = Formatter(f'{yellow}{format}{reset_color}', f2)
        self.red_fm        = Formatter(f'{red}{format}{reset_color}', f2)
        # self.red_bold_fm = Formatter(f'{red_bold}{format}{reset_color}', f2)
        # self.purple_fm   = Formatter(f'{purp}{format}{reset_color}', f2)
        self.formatters = {
            DEBUG   : self.def_fm,
            INFO    : self.def_fm,
            WARNING : self.yellow_fm,
            ERROR   : self.red_fm,
            CRITICAL: self.red_fm,
        }

    def format(self, record:LogRecord) -> str:
        formatter = self.formatters.get(record.levelno, self.def_fm)
        return formatter.format(record)


def add_log_file(loger:Logger, destination:Path, file_name:str) -> None:
    log_file = Path(destination) / f'{file_name}.log'
    cfgfile_handler = FileHandler(log_file, encoding='utf-8', mode='w')
    cfgfile_handler.setLevel(DEBUG)
    cfgfile_handler.setFormatter(RedYellowFormatter(LOG_FORMAT_CFGFILE))
    loger.addHandler(cfgfile_handler)


log = getLogger(APP_NAME)
log.setLevel(DEBUG)
stdout_handler = StreamHandler()
stdout_handler.setLevel(INFO)
stdout_handler.setFormatter(RedYellowFormatter(LOG_FORMAT_CONSOLE))
log.addHandler(stdout_handler)

#
